﻿using System;
using System.Web.Mvc;
using System.Web.Routing;

namespace TSharp.Core.Mvc.Web
{
    /// <summary>
    ///     控制器工厂
    ///     <para>2010/9/16</para>
    ///     <para>TANGJINGBO</para>
    ///     <author>tangjingbo</author>
    /// </summary>
    public class TSharpControllerFactory : DefaultControllerFactory
    {
        /// <summary>
        ///     控制器工厂
        /// </summary>
        public static readonly TSharpControllerFactory Instance = new TSharpControllerFactory();

        /// <summary>
        ///     检索指定请求上下文和控制器类型的控制器实例。
        /// </summary>
        /// <param name="requestContext">HTTP 请求的上下文，其中包括 HTTP 上下文和路由数据。</param>
        /// <param name="controllerType">控制器的类型。</param>
        /// <returns>控制器实例。</returns>
        /// <exception cref="T:System.Web.HttpException">
        ///     <paramref name="controllerType" /> 为 null。
        /// </exception>
        /// <exception cref="T:System.ArgumentException">
        ///     不能分配 <paramref name="controllerType" />。
        /// </exception>
        /// <exception cref="T:System.InvalidOperationException">
        ///     不能创建 <paramref name="controllerType" /> 的实例。
        /// </exception>
        protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
        {
            if (controllerType == null) return null;

            IController controller = base.GetControllerInstance(requestContext, controllerType);
            if (controller is Controller)
                (controller as Controller).ActionInvoker = TSharpControllerActionInvoker.Instance;
            //var container = AopContext.GetDefaultLactor();
            //return container.BuildUp(controller.GetType(), controller) as IController; 
            return controller;
        }

        public override void ReleaseController(IController controller)
        {
            base.ReleaseController(controller);
        }
    }
}